package com.mimo.common.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 主要用于生成各种随机字符串。
 *
 * @author Hongyu
 */
public final class RandomStringUtils {

  /**
   * 定义一些基本的字符库，数字和字母
   */
  protected static final List<String> RANDON_CHARS = Arrays.asList("a", "b", "c", "d", "e", "f", "i", "j", "k", "l",
      "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I",
      "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

  protected static final List<String> RANDON_NUMBERS = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");

  protected static final List<String> RANDOM_MIXED = new ArrayList<String>() {
    private static final long serialVersionUID = 1L;

    {
      addAll(RANDON_CHARS);
      addAll(RANDON_NUMBERS);
    }
  };

  /**
   * 直接返回UUID32位编码
   * 
   * @return
   */
  public static String uniqueRandom() {
    return UUID.randomUUID().toString().replace("-", "");
  }

  public static String random(RandomType type, int length) {

    ThreadLocalRandom random = ThreadLocalRandom.current();

    List<String> ret = new ArrayList<>(length);

    List<String> sourceList;

    switch (type) {
      case NUMBER:
        sourceList = RANDON_NUMBERS;
        break;
      case CHARS:
        sourceList = RANDON_CHARS;
        break;
      default:
        sourceList = RANDOM_MIXED;
        break;
    }

    for (int i = 0; i < length; i++) {
      ret.add(sourceList.get(random.nextInt(sourceList.size())));
    }

    return ret.stream().collect(Collectors.joining());
  }

  public enum RandomType {
    NUMBER, // 用于标记生成的随机串为 数字生成
    CHARS, // 用字母生成
    MIXED // 混用字母和数字生成
  }
}
